﻿Imports SIGI.Common
Imports SIGI.Common.BE
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.IO

Public Class PropertyDAC

#Region "<< -SearchPropertiesTypes- >>"
    Public Shared Function SearchPropertiesTypes() As List(Of PropertyTypeBE)
        Dim wSqlConn As SqlConnection = Nothing
        Dim wSqlCmd As SqlCommand = Nothing
        Dim wReader As SqlDataReader = Nothing
        Dim wConnStr As String = String.Empty

        Dim wPropertiesTypes As List(Of PropertyTypeBE) = Nothing
        Dim wPropertyType As PropertyTypeBE = Nothing

        Try
            'Obtengo la cadena de conexión
            wConnStr = ConfigurationManager.ConnectionStrings("connString").ConnectionString
            'Creo la conexión a la BD
            wSqlConn = New SqlConnection(wConnStr)
            'Creo el comando
            wSqlCmd = New SqlCommand()
            wSqlCmd.Connection = wSqlConn
            wSqlCmd.CommandType = CommandType.StoredProcedure
            wSqlCmd.CommandText = "TiposInmueble_s"

            wSqlConn.Open()

            wReader = wSqlCmd.ExecuteReader()
            wPropertiesTypes = New List(Of PropertyTypeBE)
            While wReader.Read()
                wPropertyType = New PropertyTypeBE
                wPropertyType.Id = Convert.ToInt32(wReader("Tipo_Inmueble"))
                wPropertyType.Description = Convert.ToString(wReader("Descripcion"))

                wPropertiesTypes.Add(wPropertyType)
            End While
            wSqlConn.Close()
        Catch ex As Exception
            Throw ex
        End Try

        Return wPropertiesTypes
    End Function
#End Region

#Region "<<- SearchByOwnerId- >>"
    Public Shared Function SearchByOwnerId(pOwnerId As Integer) As List(Of PropertyBE)
        Dim wSqlConn As SqlConnection = Nothing
        Dim wSqlCmd As SqlCommand = Nothing
        Dim wReader As SqlDataReader = Nothing
        Dim wConnStr As String = String.Empty

        Dim wProperties As List(Of PropertyBE) = Nothing
        Dim wProperty As PropertyBE = Nothing

        Try
            'Obtengo la cadena de conexión
            wConnStr = ConfigurationManager.ConnectionStrings("connString").ConnectionString
            'Creo la conexión a la BD
            wSqlConn = New SqlConnection(wConnStr)
            'Creo el comando
            wSqlCmd = New SqlCommand()
            wSqlCmd.Connection = wSqlConn
            wSqlCmd.CommandType = CommandType.StoredProcedure
            wSqlCmd.CommandText = "Propiedades_s_PorIdPropietario"

            wSqlCmd.Parameters.Add("@IdPropietario", SqlDbType.Int)
            wSqlCmd.Parameters("@IdPropietario").Value = pOwnerId

            wSqlConn.Open()

            wReader = wSqlCmd.ExecuteReader()
            wProperties = New List(Of PropertyBE)
            While wReader.Read()
                wProperty = New PropertyBE With {.OwnerId = pOwnerId}

                With wProperty
                    .Id = Convert.ToInt32(wReader("Id_Propiedad"))
                    .Name = Convert.ToString(wReader("Nombre"))
                    If Not wReader("Motivo_Baja") Is DBNull.Value Then
                        .AccountCloseMotive = Convert.ToString(wReader("Motivo_Baja"))
                    End If
                    If Not wReader("Fecha_Baja") Is DBNull.Value Then
                        .EndDate = Convert.ToDateTime(wReader("Fecha_Baja"))
                    End If
                    If Not wReader("Descripcion") Is DBNull.Value Then
                        .Description = Convert.ToString(wReader("Descripcion"))
                    End If
                    .Status = New PropertyStatusBE With {.Id = Convert.ToInt32(wReader("Id_Estado"))}
                    .Type = New PropertyTypeBE With {.Id = Convert.ToInt32(wReader("Tipo_Inmueble"))}
                    .Direction = Convert.ToString(wReader("Ubicacion"))
                    .City = New CityBE With {.Id = Convert.ToInt32(wReader("Id_Ciudad"))}
                    If Not wReader("Observaciones") Is DBNull.Value Then
                        .Observations = Convert.ToString(wReader("Observaciones"))
                    End If
                    .Province = New ProvinceBE With {.Id = Convert.ToInt32(wReader("Id_Provincia"))}
                    .Country = New CountryBE With {.Id = Convert.ToInt32(wReader("Id_Pais"))}
                    If Not wReader("Id_Contrato") Is DBNull.Value Then
                        .IdContract = Convert.ToInt32(wReader("Id_Contrato"))
                    End If
                    If Not wReader("ImagenPortada") Is DBNull.Value Then
                        .MainImage = Convert.ToString(wReader("ImagenPortada"))
                    End If
                    .SecundaryImages = SearchSecundaryImages(.Id)
                    .Services = ServicesDAC.SearchByPropertyId(.Id)
                End With

                wProperties.Add(wProperty)
            End While
            wSqlConn.Close()
        Catch ex As Exception
            Throw ex
        End Try

        Return wProperties
    End Function
#End Region

#Region "<< -SearchSecundaryImages- >>"
    Public Shared Function SearchSecundaryImages(pPropertyId As Integer) As List(Of ImagesPerPropertyBE)
        Dim wSqlConn As SqlConnection = Nothing
        Dim wSqlCmd As SqlCommand = Nothing
        Dim wReader As SqlDataReader = Nothing
        Dim wConnStr As String = String.Empty

        Dim wImages As List(Of ImagesPerPropertyBE) = Nothing
        Dim wImage As ImagesPerPropertyBE = Nothing

        Try
            'Obtengo la cadena de conexión
            wConnStr = ConfigurationManager.ConnectionStrings("connString").ConnectionString
            'Creo la conexión a la BD
            wSqlConn = New SqlConnection(wConnStr)
            'Creo el comando
            wSqlCmd = New SqlCommand()
            wSqlCmd.Connection = wSqlConn
            wSqlCmd.CommandType = CommandType.StoredProcedure
            wSqlCmd.CommandText = "ImagenesXPropiedades_g_PorIdPropiedad"

            wSqlCmd.Parameters.Add("@IdPropiedad", SqlDbType.Int)
            wSqlCmd.Parameters("@IdPropiedad").Value = pPropertyId

            wSqlConn.Open()

            wReader = wSqlCmd.ExecuteReader()
            wImages = New List(Of ImagesPerPropertyBE)
            While wReader.Read()
                wImage = New ImagesPerPropertyBE With {.IdProperty = pPropertyId}
                wImage.Id = Convert.ToInt32(wReader("Id"))
                wImage.Description = Convert.ToString("Imagen")

                wImages.Add(wImage)
            End While
        Catch ex As Exception
            Throw ex
        End Try

        Return wImages
    End Function
#End Region

#Region "<< -SearchByFilters- >>"
    Public Shared Function SearchByFilters(pIdProperty As Integer?, pOwner As String, pDirection As String, pName As String, pActive As Boolean) As DataTable
        Dim wSqlConn As SqlConnection = Nothing
        Dim wSqlCmd As SqlCommand = Nothing
        Dim wDataAdpter As SqlDataAdapter = Nothing
        Dim wConnStr As String = String.Empty
        Dim wDt As DataTable = Nothing

        Try
            'Obtengo la cadena de conexión
            wConnStr = ConfigurationManager.ConnectionStrings("connString").ConnectionString
            'Creo la conexión a la BD
            wSqlConn = New SqlConnection(wConnStr)
            'Creo el comando
            wSqlCmd = New SqlCommand()
            wSqlCmd.Connection = wSqlConn
            wSqlCmd.CommandType = CommandType.StoredProcedure
            wSqlCmd.CommandText = "Propiedades_sByParams"

            wSqlCmd.Parameters.Add("@IdPropiedad", SqlDbType.Int).Value = pIdProperty
            If Not String.IsNullOrEmpty(pOwner) Then
                wSqlCmd.Parameters.Add("@Propietario", SqlDbType.NVarChar, 100).Value = pOwner
            End If
            If Not String.IsNullOrEmpty(pDirection) Then
                wSqlCmd.Parameters.Add("@Ubicacion", SqlDbType.NVarChar, 500).Value = pDirection
            End If
            If Not String.IsNullOrEmpty(pName) Then
                wSqlCmd.Parameters.Add("@Nombre", SqlDbType.NVarChar, 50).Value = pName
            End If
            wSqlCmd.Parameters.Add("@Activa", SqlDbType.Bit).Value = pActive

            wSqlConn.Open()
            wDt = New DataTable()
            wDataAdpter = New SqlDataAdapter(wSqlCmd)
            wDataAdpter.Fill(wDt)
            wSqlConn.Close()

        Catch ex As Exception
            Throw ex
        End Try

        Return wDt
    End Function

#End Region

#Region "<< -SearchByPropertyId- >>"
    Public Shared Function SearchByPropertyId(pIdProperty As Integer) As PropertyBE
        Dim wSqlConn As SqlConnection = Nothing
        Dim wSqlCmd As SqlCommand = Nothing
        Dim wReader As SqlDataReader = Nothing
        Dim wConnStr As String = String.Empty

        Dim wProperty As PropertyBE = Nothing
        Dim wImg As ImagesPerPropertyBE = Nothing

        Try
            'Obtengo la cadena de conexión
            wConnStr = ConfigurationManager.ConnectionStrings("connString").ConnectionString
            'Creo la conexión a la BD
            wSqlConn = New SqlConnection(wConnStr)
            'Creo el comando
            wSqlCmd = New SqlCommand()
            wSqlCmd.Connection = wSqlConn
            wSqlCmd.CommandType = CommandType.StoredProcedure
            wSqlCmd.CommandText = "Propiedades_s_PorIdPropiedad"

            wSqlCmd.Parameters.Add("@IdPropiedad", SqlDbType.Int).Value = pIdProperty

            wSqlConn.Open()

            wReader = wSqlCmd.ExecuteReader()
            If wReader.Read() Then
                wProperty = New PropertyBE With {.Id = pIdProperty}

                With wProperty
                    .OwnerId = Convert.ToInt32(wReader("Id_Propietario"))
                    .Name = Convert.ToString(wReader("Nombre"))
                    If Not wReader("Motivo_Baja") Is DBNull.Value Then
                        .AccountCloseMotive = Convert.ToString(wReader("Motivo_Baja"))
                    End If
                    If Not wReader("Fecha_Baja") Is DBNull.Value Then
                        .EndDate = Convert.ToDateTime(wReader("Fecha_Baja"))
                    End If
                    If Not wReader("Descripcion") Is DBNull.Value Then
                        .Description = Convert.ToString(wReader("Descripcion"))
                    End If
                    .Status = New PropertyStatusBE With {.Id = Convert.ToInt32(wReader("Id_Estado"))}
                    .Type = New PropertyTypeBE With {.Id = Convert.ToInt32(wReader("Tipo_Inmueble"))}
                    .Direction = Convert.ToString(wReader("Ubicacion"))
                    .City = New CityBE With {.Id = Convert.ToInt32(wReader("Id_Ciudad"))}
                    If Not wReader("Observaciones") Is DBNull.Value Then
                        .Observations = Convert.ToString(wReader("Observaciones"))
                    End If
                    .Province = New ProvinceBE With {.Id = Convert.ToInt32(wReader("Id_Provincia"))}
                    .Country = New CountryBE With {.Id = Convert.ToInt32(wReader("Id_Pais"))}
                    If Not wReader("Id_Contrato") Is DBNull.Value Then
                        .IdContract = Convert.ToInt32(wReader("Id_Contrato"))
                    End If
                    If Not wReader("ImagenPortada") Is DBNull.Value Then
                        .MainImage = Convert.ToString(wReader("ImagenPortada"))
                    End If
                    .SecundaryImages = SearchSecundaryImages(.Id)
                    .Services = ServicesDAC.SearchByPropertyId(.Id)
                End With

            End If

            wReader.Close()
            wSqlCmd.CommandText = "ImagenesXPropiedades_g_PorIdPropiedad"

            wProperty.SecundaryImages = New List(Of ImagesPerPropertyBE)
            wReader = wSqlCmd.ExecuteReader()
            While wReader.Read()
                wImg = New ImagesPerPropertyBE With {.IdProperty = pIdProperty}
                wImg.Id = Convert.ToInt32(wReader("Id"))
                wImg.Description = Convert.ToString(wReader("Imagen"))

                wProperty.SecundaryImages.Add(wImg)
            End While

            wSqlConn.Close()
        Catch ex As Exception
            Throw ex
        End Try

        Return wProperty
    End Function
#End Region

#Region "<< -Delete- >>"
    Public Shared Sub Delete(pProperty As PropertyBE)
        Dim wSqlConn As SqlConnection = Nothing
        Dim wSqlCmd As SqlCommand = Nothing
        Dim wConnStr As String = String.Empty
        Dim wDirectory As String = String.Empty

        Try
            'Obtengo la cadena de conexión
            wConnStr = ConfigurationManager.ConnectionStrings("connString").ConnectionString
            'Creo la conexión a la BD
            wSqlConn = New SqlConnection(wConnStr)
            'Creo el comando
            wSqlCmd = New SqlCommand()
            wSqlCmd.Connection = wSqlConn
            wSqlCmd.CommandType = CommandType.StoredProcedure
            wSqlCmd.CommandText = "Propiedades_d"

            wSqlCmd.Parameters.Add("@IdPropiedad", SqlDbType.Int).Value = pProperty.Id
            wSqlCmd.Parameters.Add("@MotivoBaja", SqlDbType.NVarChar, 50).Value = pProperty.AccountCloseMotive

            wSqlConn.Open()
            wSqlCmd.ExecuteNonQuery()
            wSqlConn.Close()

            'Elimino el directorio de imagenes de esta propiedad
            wDirectory = Path.Combine(Common.Constants.PropertiesImagesDirectory, pProperty.Id.ToString())
            If Directory.Exists(wDirectory) Then Directory.Delete(wDirectory, True)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub
#End Region

#Region "<< -Update- >>"
    Public Shared Sub Update(pProperty As PropertyBE)
        Dim wSqlConn As SqlConnection = Nothing
        Dim wSqlCmd As SqlCommand = Nothing
        Dim wSqlTran As SqlTransaction = Nothing
        Dim wConnStr As String = String.Empty
        Dim wDirectory As String = String.Empty, wImgName = String.Empty, wMainImg = String.Empty
        Dim wStrBuilder As System.Text.StringBuilder = Nothing
        Dim wFiles As String() = Nothing
        Dim wDeleteMainImg As Boolean = False
        Dim wTmp As List(Of String) = Nothing
        Dim wFInfo As FileInfo = Nothing

        Try
            'Ruta el directorio de imagenes para esta propiedad
            wDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Common.Constants.PropertiesImagesDirectory, pProperty.Id.ToString())
            wFiles = Directory.GetFiles(wDirectory)

            'Obtengo la cadena de conexión
            wConnStr = ConfigurationManager.ConnectionStrings("connString").ConnectionString
            'Creo la conexión a la BD
            wSqlConn = New SqlConnection(wConnStr)
            'Creo el comando
            wSqlCmd = New SqlCommand()
            wSqlCmd.Connection = wSqlConn
            wSqlCmd.CommandType = CommandType.StoredProcedure

            wSqlConn.Open()
            'Creo la transacción
            wSqlTran = wSqlConn.BeginTransaction("Transaction")
            wSqlCmd.Transaction = wSqlTran

            wSqlCmd.CommandText = "[dbo].[ServiciosXPropiedades_d]"
            wSqlCmd.Parameters.Add("@Id_Propiedad", SqlDbType.Int).Value = pProperty.Id.Value

            wSqlCmd.ExecuteNonQuery()

            wSqlCmd.CommandText = "[dbo].[ImagenesXPropiedades_d]"
            wSqlCmd.ExecuteNonQuery()

            wSqlCmd.CommandText = "[dbo].[Propiedades_u]"

            If String.IsNullOrEmpty(pProperty.Description) Then
                wSqlCmd.Parameters.Add("@Descripcion", SqlDbType.Char, 100).Value = DBNull.Value
            Else
                wSqlCmd.Parameters.Add("@Descripcion", SqlDbType.Char, 100).Value = pProperty.Description
            End If
            wSqlCmd.Parameters.Add("@Id_Estado", SqlDbType.Int).Value = pProperty.Status.Id
            wSqlCmd.Parameters.Add("@Tipo_Inmueble", SqlDbType.Int).Value = pProperty.Type.Id
            wSqlCmd.Parameters.Add("@Ubicacion", SqlDbType.Char, 100).Value = pProperty.Direction
            wSqlCmd.Parameters.Add("@Id_Ciudad", SqlDbType.Int).Value = pProperty.City.Id
            If (String.IsNullOrEmpty(pProperty.Observations)) Then
                wSqlCmd.Parameters.Add("@Observaciones", SqlDbType.VarChar, 150).Value = DBNull.Value
            Else
                wSqlCmd.Parameters.Add("@Observaciones", SqlDbType.VarChar, 150).Value = pProperty.Observations
            End If
            wSqlCmd.Parameters.Add("@Id_Propietario", SqlDbType.Int).Value = pProperty.OwnerId
            wSqlCmd.Parameters.Add("@Id_Provincia", SqlDbType.Int).Value = pProperty.Province.Id
            wSqlCmd.Parameters.Add("@Id_Pais", SqlDbType.Int).Value = pProperty.Country.Id
            If Not String.IsNullOrEmpty(pProperty.MainImage) Then
                'Ubicación de la portada
                wFInfo = New FileInfo(pProperty.MainImage)
                wMainImg = Path.Combine(wDirectory, wFInfo.Name)
                If pProperty.MainImage <> wMainImg Then File.Copy(pProperty.MainImage, wMainImg, True)

                wSqlCmd.Parameters.Add("@Portada", SqlDbType.NVarChar, 5000).Value = wMainImg
            Else
                wDeleteMainImg = True
            End If

            wSqlCmd.ExecuteNonQuery()

            wSqlCmd.CommandType = CommandType.Text
            If Not pProperty.Services Is Nothing Then
                wStrBuilder = New System.Text.StringBuilder
                For Each wSrv As ServicesBE In pProperty.Services
                    wStrBuilder.Append("EXEC [dbo].[ServiciosXPropiedades_i]")
                    wStrBuilder.Append(String.Format(" @Id_Propiedad = {0}, ", pProperty.Id))
                    wStrBuilder.Append(String.Format(" @Id_Servicio = {0} ", wSrv.Id))
                    wStrBuilder.AppendLine()
                Next
                If wStrBuilder.Length > 0 Then
                    wSqlCmd.CommandText = wStrBuilder.ToString()
                    wSqlCmd.ExecuteNonQuery()
                End If
            End If

            If Not pProperty.SecundaryImages Is Nothing Then
                wStrBuilder.Clear()
                wTmp = New List(Of String)
                For Each wImg As ImagesPerPropertyBE In pProperty.SecundaryImages
                    'Obtengo el nombre de la imágen
                    wImgName = wImg.Description.Substring(wImg.Description.LastIndexOf("\") + 1)
                    'Creo la imagen
                    wImgName = Path.Combine(wDirectory, wImgName)

                    If Not wFiles.ToList().Exists(Function(f) f = wImgName) Then
                        File.Copy(wImg.Description, wImgName, True)
                    End If

                    wStrBuilder.Append("EXEC ImagenesXPropiedades_i ")
                    wStrBuilder.Append(String.Format(" @Id_Propiedad = {0}, ", pProperty.Id))
                    wStrBuilder.Append(String.Format(" @Imagen = '{0}' ", wImgName))
                    wStrBuilder.AppendLine()

                    wTmp.Add(wImgName)
                Next

                If wStrBuilder.Length > 0 Then
                    wSqlCmd.CommandText = wStrBuilder.ToString()
                    wSqlCmd.ExecuteNonQuery()
                End If

                'Elimino las imaneges innecesarias
                wFiles = Directory.GetFiles(wDirectory)
                For Each wFile As String In wFiles
                    If Not wTmp.Exists(Function(img) img = wFile) And wFile <> wMainImg Then
                        File.Delete(wFile)
                    End If
                Next
            End If

            wSqlTran.Commit()

            wSqlConn.Close()
        Catch ex As Exception
            Try
                wSqlTran.Rollback()
                Throw ex
            Catch ex2 As Exception
                Throw ex2
            End Try
        End Try
    End Sub
#End Region

#Region "<< -InsertBatch- >>"
    Public Shared Sub InsertBatch(pProperties As List(Of PropertyBE))
        Dim wSqlConn As SqlConnection = Nothing
        Dim wSqlCmd As SqlCommand = Nothing
        Dim wSqlTran As SqlTransaction = Nothing
        Dim wReader As SqlDataReader = Nothing
        Dim wConnStr As String = String.Empty
        Dim wDirectory As String = String.Empty, wImgName = String.Empty, wMainImg = String.Empty
        Dim wQuery As System.Text.StringBuilder = Nothing
        Dim wQueryImg As System.Text.StringBuilder = Nothing
        Dim wQuerySvc As System.Text.StringBuilder = Nothing
        Dim wFInfo As FileInfo = Nothing

        Try
            'Obtengo la cadena de conexión
            wConnStr = ConfigurationManager.ConnectionStrings("connString").ConnectionString
            'Creo la conexión a la BD
            wSqlConn = New SqlConnection(wConnStr)
            'Creo el comando
            wSqlCmd = New SqlCommand()
            wSqlCmd.Connection = wSqlConn

            wSqlConn.Open()
            'Creo la transacción
            wSqlTran = wSqlConn.BeginTransaction("Transaction")
            wSqlCmd.Transaction = wSqlTran

            wQuery = New System.Text.StringBuilder
            wQueryImg = New System.Text.StringBuilder
            wQuerySvc = New System.Text.StringBuilder
            For Each wProperty As PropertyBE In pProperties
                wQuery.Clear()

                'Servicios de la propiedad
                If Not wProperty.Services Is Nothing Then
                    wQuerySvc.Clear()
                    For Each wSrv As ServicesBE In wProperty.Services
                        wQuerySvc.Append("EXEC ServiciosXPropiedades_i ")
                        wQuerySvc.Append(" @Id_Propiedad = [Id_Propiedad], ")
                        wQuerySvc.Append(String.Format(" @Id_Servicio = {0} ", wSrv.Id))
                        wQuerySvc.AppendLine()
                    Next
                End If

                wQuery.Append("EXEC Propiedades_i ")
                wQuery.Append(String.Format(" @Nombre = '{0}', ", wProperty.Name))
                If String.IsNullOrEmpty(wProperty.Description) Then
                    wQuery.Append(" @Descripcion = NULL, ")
                Else
                    wQuery.Append(String.Format(" @Descripcion = '{0}', ", wProperty.Description))
                End If
                wQuery.Append(String.Format(" @Id_Estado = {0}, ", wProperty.Status.Id))
                wQuery.Append(String.Format(" @Tipo_Inmueble = {0}, ", wProperty.Type.Id))
                wQuery.Append(String.Format(" @Ubicacion = '{0}', ", wProperty.Direction))
                wQuery.Append(String.Format(" @Id_Ciudad = {0}, ", wProperty.City.Id))
                If (String.IsNullOrEmpty(wProperty.Observations)) Then
                    wQuery.Append(" @Observaciones = NULL, ")
                Else
                    wQuery.Append(String.Format(" @Observaciones = '{0}', ", wProperty.Observations))
                End If
                wQuery.Append(String.Format(" @Id_Propietario = {0}, ", wProperty.OwnerId))
                wQuery.Append(String.Format(" @Id_Provincia = {0}, ", wProperty.Province.Id))
                wQuery.Append(String.Format(" @Id_Pais = {0}, ", wProperty.Country.Id))
                wQuery.Append(" @Id_Contrato = NULL, ")
                If wQuerySvc.Length > 0 Then
                    wQuery.Append(String.Format("@Servicios = '{0}' ", wQuerySvc.ToString()))
                Else
                    wQuery.Append("@Servicios = NULL ")
                End If

                wQuery.AppendLine()

                wSqlCmd.CommandText = wQuery.ToString()
                wReader = wSqlCmd.ExecuteReader()
                wReader.Read()
                wProperty.Id = Convert.ToInt32(wReader(0))
                wReader.Close()

                'Ruta el directorio de imagenes para esta propiedad
                wDirectory = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, Common.Constants.PropertiesImagesDirectory, wProperty.Id.ToString())
                'Creo el directorio de imágenes si no la cree al crear el propietario
                Directory.CreateDirectory(wDirectory)
                'Ubicación de la portada
                If Not String.IsNullOrEmpty(wProperty.MainImage) Then
                    wFInfo = New FileInfo(wProperty.MainImage)
                    wImgName = Path.Combine(wDirectory, wFInfo.Name)
                    'Guardo la imagen de la portada
                    File.Copy(wProperty.MainImage, wImgName, True)

                    wSqlCmd.CommandType = CommandType.Text

                    wSqlCmd.CommandText = String.Format("UPDATE dbo.Propiedades SET ImagenPortada = '{0}' WHERE Id_Propiedad = {1}",
                                                        wImgName, wProperty.Id)
                End If

                wSqlCmd.ExecuteNonQuery()

                'Imagenes de la propiedad
                If wProperty.SecundaryImages Is Nothing Then Continue For
                For Each wImg As ImagesPerPropertyBE In wProperty.SecundaryImages
                    'Obtengo el nombre de la imágen
                    wImgName = wImg.Description.Substring(wImg.Description.LastIndexOf("\") + 1)
                    'Creo la imagen
                    wImgName = Path.Combine(wDirectory, wImgName)
                    File.Copy(wImg.Description, wImgName, True)

                    wQueryImg.Append("EXEC ImagenesXPropiedades_i ")
                    wQueryImg.Append(String.Format(" @Id_Propiedad = {0}, ", wProperty.Id))
                    wQueryImg.Append(String.Format(" @Imagen = '{0}' ", wImgName))
                    wQuery.AppendLine()
                Next
            Next
            'Inserto la imagenes de todas las propiedades en la base
            If wQueryImg.Length > 0 Then
                wSqlCmd.CommandText = wQueryImg.ToString()
                wSqlCmd.ExecuteNonQuery()
            End If

            wSqlTran.Commit()

            wSqlConn.Close()

        Catch ex As Exception
            Try
                If Not String.IsNullOrEmpty(wDirectory) AndAlso Directory.Exists(wDirectory) Then
                    Directory.Delete(wDirectory, True)
                End If
                wSqlTran.Rollback()
                Throw ex
            Catch ex2 As Exception
                Throw ex2
            End Try
        End Try
    End Sub
#End Region

End Class
